import React from 'react';
import {Button, Form, Input} from 'antd';
import {useModel, useNavigate, useRequest} from 'umi';
import {userAuthApi} from '@/services/login/LoginController';
import styles from './index.less';

interface LoginFormData {
  loginName: string;
  password: string;
}

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const { refresh } = useModel('@@initialState');
  const navigate = useNavigate();
  const { run: loginRequest } = useRequest<API.LoginParams>(
    async (params) => {
      const { loginName, password } = params;
      const response = await userAuthApi({ loginName, password });
      // 登录成功，刷新 initialState
      // await refresh();
      return response;
    },
    {
      manual: true, // 手动触发请求
      onSuccess: (data, params) => {
        const { token } = data;
        // 设置token
        // console.log("token:"+token);
        // console.log("process.env.TOKEN_LOCAL_STORAGE_NAME:"+process.env.TOKEN_LOCAL_STORAGE_NAME);
        localStorage.setItem(process.env.TOKEN_LOCAL_STORAGE_NAME,token);
        // 登录成功后的逻辑，如跳转到首页、
          // const { refresh } = useModel('@@initialState');
  //      // 登录成功，刷新 initialState
        refresh().then(() => {
            console.log('完成刷新 initialState');
          })
          .catch((error) => {
            console.error('刷新 initialState 失败:', error);
        });
        navigate('/home', { replace: true });
        // navigate(-1);
      },

    },
  );

  const handleSubmit = async (values: LoginFormData) => {
    try {
      await loginRequest(values);
    } catch (error) {
      // message.error('请求发生错误');
    }
  };

  return (
    <div className={styles.login}>
      <div className={styles.title}><h1>登录</h1></div>
      <div className={styles.input}>
        <Form form={form} onFinish={handleSubmit}>
          <Form.Item
            name="loginName"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
